package com.lam.communication;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lam.fundamental.R;

public class DailActivity extends Activity{

	private Button bt_dail;
	private EditText et_phone;
	private AutoCompleteTextView phoneNumber;
	private Cursor contract;
	private ContactAdapter myAdapter;
	
	
	public static final String [] PEOPLE_PROJECTION=new String[]{
		Contacts.People._ID,Contacts.People.PRIMARY_PHONE_ID,
		Contacts.People.TYPE,Contacts.People.NUMBER,Contacts.People.LABEL,
		Contacts.People.NAME
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dail);
		bt_dail = (Button)findViewById(R.id.bt_dail);
		et_phone = (EditText)findViewById(R.id.et_phoneNumber);
		phoneNumber=(AutoCompleteTextView)findViewById(R.id.ac_phoneNumber);
		
		
		ContentResolver contentResolver=getContentResolver();
		
		contract = contentResolver.query(
				Contacts.People.CONTENT_URI,
				PEOPLE_PROJECTION,
				null, null, Contacts.People.DEFAULT_SORT_ORDER);
		
		myAdapter=new ContactAdapter(this, contract);
		Log.i("sdfasd","dldsldf");
		phoneNumber.setAdapter(myAdapter);
		
		phoneNumber.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Cursor cursor=myAdapter.getCursor();
				
				cursor.moveToPosition(position);
				String number=cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NUMBER));
				number= number==null?"no phone number inputed":number;
				et_phone.setText(cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NUMBER)));
			}
			
		});
		
		bt_dail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					String phoneNumber=et_phone.getText().toString().trim();
					if(isPhoneNumberValid(phoneNumber)){
						Intent dailIntent = new Intent("android.intent.action.CALL"
								,Uri.parse("tel:"+phoneNumber));
						startActivity(dailIntent);
						
					}else{
						Toast.makeText(DailActivity.this, "phone number format error!",
								Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
				
			}

			private boolean isPhoneNumberValid(String phoneNumber) {
				// TODO Auto-generated method stub
				boolean isValid = false;
				
				/*
				 * formate (123)456-78900 123-4560-7890 12345678900 (123)-4567-8900
				 */
				String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
				String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
				CharSequence inputStr=phoneNumber;
				Pattern pattern=Pattern.compile(expression);
				Matcher matcher=pattern.matcher(inputStr);
				
				Pattern pattern2=Pattern.compile(expression2);
				Matcher matcher2=pattern2.matcher(inputStr);
				if(matcher.matches()||matcher2.matches()){
					isValid=true;
				}
				return isValid;
			}
		});
		
	}
	
	class ContactAdapter extends CursorAdapter{
		private ContentResolver mContentResolver;
		
		public ContactAdapter(Context context,Cursor cursor){
			super(context,cursor);
			mContentResolver = context.getContentResolver();
			
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			// TODO Auto-generated method stub
			((TextView)view).setText(cursor.getString(cursor.
					getColumnIndexOrThrow(Contacts.People.NAME)));
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			// TODO Auto-generated method stub
			final LayoutInflater inflater=LayoutInflater.from(context);
			final TextView view = (TextView)inflater.inflate(
					android.R.layout.simple_dropdown_item_1line,parent,false);
			view.setText(cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME)));
			
			return view;
		}

		@Override
		public CharSequence convertToString(Cursor cursor) {
			// TODO Auto-generated method stub
			return cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME));
			
		}

		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
			// TODO Auto-generated method stub
			if(getFilterQueryProvider()!=null){
				return getFilterQueryProvider().runQuery(constraint);
			}
			StringBuffer buffer =null;
			Log.i("sdfasd","aaaa333333333aaa");
			String [] arg=null;
			if(constraint!=null){
				buffer.append("UPPER(");
				buffer.append(Contacts.ContactMethods.NAME);
				buffer.append(") GLOB ?");
				arg=new String[]{
						constraint.toString().toUpperCase()+"*"
				};
				
			}
			
			return mContentResolver.query(Contacts.People.CONTENT_URI, DailActivity.PEOPLE_PROJECTION, buffer==null?null:buffer.toString(),
					arg, Contacts.People.DEFAULT_SORT_ORDER);
					
		}
		
		
		
		
		
	}
	
}
